<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
            "http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>



<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="hevea 1.08">
<LINK rel="stylesheet" type="text/css" href="embroot.css">
<TITLE>
Built-Ins
</TITLE>
</HEAD>
<BODY >
<A HREF="embroot062.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="embroot059.html"><IMG SRC ="contents_motif.gif" ALT="Up"></A>
<HR>

<H2 CLASS="section"><A NAME="htoc122">11.4</A>&nbsp;&nbsp;Built-Ins</H2><UL>
<LI><A HREF="embroot063.html#toc64">Sessions</A>
<LI><A HREF="embroot063.html#toc65">Database Updates</A>
<LI><A HREF="embroot063.html#toc66">Database Queries</A>
<LI><A HREF="embroot063.html#toc67">Parametrised Database Queries</A>
</UL>


<A NAME="toc64"></A>
<H3 CLASS="subsection"><A NAME="htoc123">11.4.1</A>&nbsp;&nbsp;Sessions</H3>

These predicates deal with sessions as a whole. A session is 
used to identify a connection to a database. Associated to that
session are a number of cursors. These are handles to SQL statements
which are currently being executed. For example a query where only
some of the matching rows have been fetched.<BR>
<BR>
Database transactions &ndash; where updates to the database are local to the
session until committed, and where uncommitted changes can be rolled back, 
are supported if the external database supports transactions<SUP><A NAME="text9" HREF="embroot059.html#note9">1</A></SUP>. <BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/session_start-4.html"><B>session_start(+Login, +Password, +Options, -Session)</B></A><A NAME="@default345"></A></H4>
<A NAME="session-start/3"></A>

This create a new session by establishing a new connections to the
database server, and associates it with a handle,
returned in Session.<BR>
<BR>
The session remains in existence in subsequent goals. It is automatically
closed if the program fails or aborts back beyond this call. The session
is used as a access handle to the database in subsequent calls to this
interface.<BR>
<BR>
The automatic closure is particularly useful in case of a
program aborting due to a runtime error. Closing the database ensures
any database updates that have not been committed will be undone.<BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/session_close-1.html"><B>session_close(+Session)</B></A><A NAME="@default346"></A></H4>
<A NAME="session-close/1"></A>

This closes a session, disconnecting from the database server. It
takes effect immediately. This allow resources allocated for the
session to be freed. To free all resources associated with a session,
all cursors of the session should also be closed with
<A HREF="../bips/lib/dbi/cursor_close-1.html"><B>cursor_close/1</B></A><A NAME="@default347"></A>. <BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/session_commit-1.html"><B>session_commit(+Session)</B></A><A NAME="@default348"></A></H4>
<A NAME="session-commit/1"></A>

If executed outside the scope of a
<A HREF="../bips/lib/dbi/session_transaction-2.html"><B>session_transaction/2</B></A><A NAME="@default349"></A>
goal, this commits any transactional updates to the database made within
 Session. 
 Otherwise, it simply succeeds without doing anything.<BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/session_rollback-1.html"><B>session_rollback(+Session)</B></A><A NAME="@default350"></A></H4>
<A NAME="session-rollback/1"></A>

If executed outside the scope of a
<A HREF="../bips/lib/dbi/session_transaction-2.html"><B>session_transaction/2</B></A><A NAME="@default351"></A>
goal,
this undoes all transactional changes made to the database since the last
commit for this session. Otherwise, it will simply abort the complete outer
transaction. (Note: not all changes can be rolled back; consult the DB manual for details)<BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/session_transaction-2.html"><B>session_transaction(+Session, +Goal)</B></A><A NAME="@default352"></A></H4>
<A NAME="session-transaction/2"></A>

This executes Goal as a database transaction. This predicate is only useful
if the database supports transactions. Data base updates within Goal are
committed if Goal succeeds; if Goal fails or aborts, the updates are rolled
back. <BR>
<BR>
Calls of this predicate can be nested, but only the outermost
transaction is real. All the inner transactions are simply
equivalent to call(Goal).
This way it is possible to write a call to
session_transaction/2, into some code that implements a simple
update, but then to include that simple update into a larger
transaction.<BR>
<BR>
Transactions are local to one session so there is no way to safely
make an update relating to several sessions.
<PRE CLASS="verbatim">
recorded_transfer(Session,Date,Amount,FromAccount,ToAccount) :-
    session_transaction(Session, (
        transfer(Session, Amount,FromAccount,ToAccount),
        check_overdraft_limit(FromAccount),
        record_transfer(Date,Amount,FromAccount,ToAccount)
    )).

transfer(Session, Amount,FromAccount,ToAccount) :-
     session_transaction(Session, 
         transfer_(Session,Amount,FromAccount,ToAccount)
     ).

</PRE>
In the above example we can see two nested transactions. One simple bank
transfer that is not recorded, and an outer transaction recording the
occurrence of the transfer and checking the balance.<BR>
<BR>
Since a nested transaction is simply a call of its goal, with no
partial rollbacks care has to be taken not to redo transactions on
failure unless one is sure one is at an outer transaction.<BR>
<BR>
<A NAME="toc65"></A>
<H3 CLASS="subsection"><A NAME="htoc124">11.4.2</A>&nbsp;&nbsp;Database Updates</H3>

For database updates, lib(dbi) provides predicates to execute SQL
statements on the database without returning results. 
<A HREF="../bips/lib/dbi/session_sql-3.html"><B>session_sql/3</B></A><A NAME="@default353"></A> executes
an SQL statement directly. <A HREF="../bips/lib/dbi/session_sql_prepare-4.html"><B>session_sql_prepare/4</B></A><A NAME="@default354"></A> is used to
prepare SQL statements, returning a cursor to the prepared statement,
which can then be executed
multiple times with different placeholder values using either
<A HREF="../bips/lib/dbi/cursor_next_execute-2.html"><B>cursor_next_execute/2</B></A><A NAME="@default355"></A> or
<A HREF="../bips/lib/dbi/cursor_all_execute-2.html"><B>cursor_all_execute/2</B></A><A NAME="@default356"></A> or
<A HREF="../bips/lib/dbi/cursor_N_execute-4.html"><B>cursor_N_execute/4</B></A><A NAME="@default357"></A>.
Cursors are automatically closed if the program backtracks or aborts beyond
the predicate that created it. Alternatively, the cursor can be closed
explicitly by <A HREF="../bips/lib/dbi/cursor_close-1.html"><B>cursor_close/1</B></A><A NAME="@default358"></A>.<BR>
<BR>
The datatypes of the parameters for the prepared statement is specified by
a template given to session_sql_prepare/4. See section&nbsp;<A HREF="embroot062.html#data-templates">11.3</A>
for details on the templates. <BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/session_sql-3.html"><B>session_sql(+Session, +SQL, -RowProcessedCount)</B></A><A NAME="@default359"></A></H4>
<A NAME="session-sql/3"></A>

This is the simplest interface to execute an SQL statement with no
placeholders.
<PRE CLASS="verbatim">
make_accounts(Session) :-
    session_sql(Session,
        "create table accounts \
         (id           decimal(4)      not null,\
          balance      decimal(9,2)    default 0.0 not null, \
          overdraft    decimal(9,2)    default 0.0 not null \
         )" ,_),
    session_sql(Session,
        "insert into accounts (id,balance) values (1001,1200.0)",1),
    session_sql(Session,
        "insert into accounts (id,balance) values (1002,4300.0)",1).
</PRE>In the example we see session_sql/3 used, first to create a
table, and then to initialise it with two rows. The rows processed counts
are checked to make sure exactly one row is processed per statement.<BR>
<BR>
This code assumes a session with handle <TT>Handle</TT> has been started beforehand.<BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/session_sql_prepare-4.html"><B>session_sql_prepare(+Session, +Template, +SQL, -Cursor)</B></A><A NAME="@default360"></A></H4>
<A NAME="session-sql-prepare/4"></A>

This creates Cursor, which is a handle to the prepared statement,
possibly with placeholders. Template specifies the types of the placeholders 
(see section&nbsp;<A HREF="embroot062.html#data-templates">11.3</A>). 
<PRE CLASS="verbatim">
transfer_(Session, Amount, FromAccount, ToAccount) :-
    SQL = "update accounts set balance = balance + ? \
                                             where id = ?",
    Deduct is - Amount,
    session_sql_prepare(Session,incbal(1.0,12),SQL,1,Update),
    cursor_next_execute(Update,incbal(Deduct,FromAccount)),
    cursor_next_execute(Update,incbal(Amount,ToAccount)).
</PRE>In the example a cursor is prepared to modify account balances. It is used
twice, once to deduct an amount and once to add that same amount to
another account. Note: the example uses MySQL's syntax for prepared
statement, which may differ from other databases. Consult your database manual for
prepared statement syntax.<BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/cursor_next_execute-2.html"><B>cursor_next_execute(+Cursor, +Tuple)</B></A><A NAME="@default361"></A></H4>
<A NAME="cursor-next-execute/2"></A>

Execute the prepared SQL statement represented by Cursor, with Tuple
supplying the values for any parameter values.
This call can be executed any number of times on the same cursor.<BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/cursor_all_execute-2.html"><B>cursor_all_execute(+Cursor, +TupleList)</B></A><A NAME="@default362"></A></H4>
<A NAME="cursor-all-execute/2"></A>

The SQL statement of Cursor is executed once for each Tuple in 
TupleList. This could be defined as:
<PRE CLASS="verbatim">
cursor_all_execute( Cursor, []).
cursor_all_execute( Cursor, [Tuple | Tuples] ) :-
    cursor_next_execute(Cursor, Tuple),
    cursor_all_execute( Cursor, Tuples ).
</PRE>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/cursor_N_execute-4.html"><B>cursor_N_execute(+Cursor, -Executed, +TupleList, -RestTupleList)</B></A><A NAME="@default363"></A></H4>
<A NAME="cursor-N-execute/4"></A>

Some databases supports the execution of multiple tuples of parameter values at
once, doing this more efficiently than executing each tuple of parameter
values one by one. This predicate is provided to support this. <BR>
<BR>
Note that for databases that does not support execution of multiple tuples, this
predicate is implemented by executing the Tuples one by one as in 
<A HREF="../bips/lib/dbi/cursor_next_execute-2.html"><B>cursor_next_execute/2</B></A><A NAME="@default364"></A>,
and there is no gain in efficiency over using cursor_next_execute/2.
<PRE CLASS="verbatim">
transfer_(Session, Amount, FromAccount, ToAccount) :-
    SQL = "update accounts set balance = balance + ? \
                                             where id = ?",
    Deduct is - Amount,
    session_sql_prepare(Session,incbal(1.0,12),SQL,2,Update),
    Updates = [incbal(Deduct,FromAccount),incbal(Amount,ToAccount)],
    cursor_N_execute(Update,2,Updates,[]).
</PRE>
The example shows how to re-code the bank transfer predicate from
<A HREF="../bips/lib/dbi/cursor_next_execute-2.html"><B>cursor_next_execute/2</B></A><A NAME="@default365"></A>,
to execute
both updates with one call. This could lead to some performance
improvement in a client server setting for databases that supports multiple
parameter tuples.<BR>
<BR>
<A NAME="toc66"></A>
<H3 CLASS="subsection"><A NAME="htoc125">11.4.3</A>&nbsp;&nbsp;Database Queries</H3>

For database queries, lib(dbi) provides predicates to execute SQL
statements and extract the results returned by the database.
<A HREF="../bips/lib/dbi/session_sql_query-4.html"><B>session_sql_query/4</B></A><A NAME="@default366"></A> or
<A HREF="../bips/lib/dbi/session_sql_query-5.html"><B>session_sql_query/5</B></A><A NAME="@default367"></A> 
executes an SQL statement, returning a cursor to allow the results to be
extracted from the database. The predicates to do this are
<A HREF="../bips/lib/dbi/cursor_next_tuple-2.html"><B>cursor_next_tuple/2</B></A><A NAME="@default368"></A>,
<A HREF="../bips/lib/dbi/cursor_all_tuples-2.html"><B>cursor_all_tuples/2</B></A><A NAME="@default369"></A> and
<A HREF="../bips/lib/dbi/cursor_N_tuples-4.html"><B>cursor_N_tuples/4</B></A><A NAME="@default370"></A>.<BR>
<BR>
The datatypes of the results tuple is specified by a template given to
session_sql_query/4,5. See section&nbsp;<A HREF="embroot062.html#data-templates">11.3</A> for details on the
templates. <BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/session_sql_query-4.html"><B>session_sql_query(+Session, +Template, +SQL, -Cursor)</B></A><A NAME="@default371"></A></H4>
<A NAME="session-sql-query/5"></A>

This executes SQL and creates the handle Cursor for the SQL query. Template
specifies the datatypes of the results tuples.<BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/cursor_next_tuple-2.html"><B>cursor_next_tuple(+Cursor, -Tuple)</B></A><A NAME="@default372"></A></H4>
<A NAME="cursor-next-tuple/2"></A>

A single tuple is retrieved from the database. Calling this
predicate again with the same cursor will retrieve further tuples
Any NULL values are returned as uninstantiated variables.<BR>
<BR>
Once all the tuples have been retrieved this predicate fails.<BR>
<BR>
If Tuple does not unify with the retrieved tuple, the predicate fails.
<PRE CLASS="verbatim">
check_overdraft_limit(Session, Account) :-
    L = ["select count(id) from accounts \
        where     id = ",Account," and balance &lt; overdraft"],
    concat_string(L,SQL),
    session_sql_query(Session,c(0),SQL,OverdraftCheck),
    cursor_next_tuple(OverdraftCheck,c(Count)),
    Count = 0.
</PRE>In this example a query is built to verify that the balance of an
account is not less than its overdraft facility. All comparisons
are done within the database, and we are just interested in checking
that no rows match the 'where' clause.<BR>
<BR>
For this kind of application one would not normally use
concat_string/2. SQL placeholders would be used instead. See
<A HREF="../bips/lib/dbi/session_sql_prepare_query-5.html"><B>session_sql_prepare_query/5</B></A><A NAME="@default373"></A>.<BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/cursor_all_tuples-2.html"><B>cursor_all_tuples(+Cursor, -TupleList)</B></A><A NAME="@default374"></A></H4>
<A NAME="cursor-all-tuples/2"></A>

The SQL query represented by the cursor is executed and all
the matching tuples are collected in TupleList.<BR>
<BR>
This could be defined as:
<PRE CLASS="verbatim">
cursor_all_tuples( Cursor, Tuples ) :-
    ( cursor_next_tuple(Cursor, T) -&gt;
        Tuples = [T | Ts],
        cursor_all_tuples(Cursor, Ts)
    ;
        Tuples = []
    ).
</PRE>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/cursor_N_tuples-4.html"><B>cursor_N_tuples(+Cursor, -Retrieved, -TupleList, -RestTupleList)</B></A><A NAME="@default375"></A></H4>
<A NAME="cursor-N-tuples/4"></A>

If the underlying DB supports the retrieving mutule tuples in one go, then
a buffer full of tuples matching the query is retrieved, otherwise all the
remaining tuples are retrieved.<BR>
<BR>
TupleList and RestTupleList form a difference list containing these
tuples. Retrieved is the number of tuples retrieved.<BR>
<BR>
<A NAME="toc67"></A>
<H3 CLASS="subsection"><A NAME="htoc126">11.4.4</A>&nbsp;&nbsp;Parametrised Database Queries</H3>


The library allow SQL queries to be prepared and parameterised, if prepared
SQL statements are supported by the underlying database. Templates are needed
for specifying the datatypes of the parameters (as with
<A HREF="../bips/lib/dbi/session_sql_prepare-4.html"><B>session_sql_prepare/4</B></A><A NAME="@default376"></A>),
and for the results tuples (as with <A HREF="../bips/lib/dbi/session_sql_query-4.html"><B>session_sql_query/4</B></A><A NAME="@default377"></A>. An SQL query
is prepared by
<A HREF="../bips/lib/dbi/session_sql_prepare_query-5.html"><B>session_sql_prepare_query/5</B></A><A NAME="@default378"></A>,
it then needs to be executed by
<A HREF="../bips/lib/dbi/cursor_next_execute-2.html"><B>cursor_next_execute/2</B></A><A NAME="@default379"></A> or
<A HREF="../bips/lib/dbi/cursor_next_execute-3.html"><B>cursor_next_execute/3</B></A><A NAME="@default380"></A>
(cursor_next_execute/3 allows the specification of options for the cursor),
and the results can then be retrieved by <A HREF="../bips/lib/dbi/cursor_next_tuple-2.html"><B>cursor_next_tuple/2</B></A><A NAME="@default381"></A>,
<A HREF="../bips/lib/dbi/cursor_all_tuples-2.html"><B>cursor_all_tuples/2</B></A><A NAME="@default382"></A> and
<A HREF="../bips/lib/dbi/cursor_N_tuples-4.html"><B>cursor_N_tuples/4</B></A><A NAME="@default383"></A>. After
executing cursor_next_execute/2, it can be executed again with a new tuple
of parameter values. Any unretrieved results from the previous execute are
discarded. Note that this is non-logical: the discarded results are not
recovered on backtracking.
<BR>
<BR>

<H4 CLASS="subsubsection"><A HREF="../bips/lib/dbi/session_sql_prepare_query-5.html"><B>session_sql_prepare_query(+Session, +ParamT, +QueryT, +SQL,-Cursor)</B></A><A NAME="@default384"></A></H4>
<A NAME="session-prepare-sql-query/5"></A>

This creates Cursor, which is a handle to the prepared SQL query.<BR>
<BR>
By changing the placeholders one gets a fresh query and can start extracting
tuples again.<BR>
<BR>
In this example a generic query is built to check whether an account is
overdrawn, and a cursor for this query is created.
<PRE CLASS="verbatim">
make_check_overdraft_limit(Session, Cursor) :-
    SQL = "select count(id) from accounts where ID = ? \
               and balance &lt; overdraft",
    session_sql_prepare_query(Session,a(0),c(0),SQL,1,Cursor).

check_overdraft_limit(Check,Account) :-
    cursor_next_execute(Check,a(Account)),
    cursor_next_tuple(Check,c(Count)),
    Count = 0.
</PRE>The check_overdraft_limit/2 predicate uses the cursor to check an account.
This cursor can be re-used to check any number of accounts.<BR>
<BR>
<A NAME="@default385"></A>
<A NAME="@default386"></A>
<HR>
<A HREF="embroot062.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="embroot059.html"><IMG SRC ="contents_motif.gif" ALT="Up"></A>
</BODY>
</HTML>
